package com.bbx.demo.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WebSocketServer {
    private int port = 8093;

    public WebSocketServer()  {

    }

    public static void main (String [] args) throws InterruptedException {
        WebSocketServerHandler webSocketServerHandler = new WebSocketServerHandler();
        new WebSocketServer().start(webSocketServerHandler);
    }
    private void start(ChannelHandler channelHandler) throws InterruptedException {
        NioEventLoopGroup bossEventExecutors = new NioEventLoopGroup();
        NioEventLoopGroup workerEventExecutors = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossEventExecutors, workerEventExecutors)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    //成为一个Http服务
                                    .addLast(new HttpServerCodec())
                                    //以块的方式进行写，以便于大量数据传输时不消耗大量的内存
                                    .addLast(new ChunkedWriteHandler())
                                    //HTTP 对象聚合，将多块传输的聚合在一起
                                    .addLast(new HttpObjectAggregator(2018))
                                    //将Http请求处理为Websocket
                                    .addLast(new WebSocketServerProtocolHandler("/bbx"))
                                    .addLast(channelHandler);
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossEventExecutors.shutdownGracefully();
            workerEventExecutors.shutdownGracefully();
        }
    }
}
